package com.srp.controller;


import com.srp.common.R;
import com.srp.pojo.CreateOrLoginReturn;
import com.srp.pojo.EditUserInfoReturn;
import com.srp.pojo.GetUserInfoReturn;
import com.srp.servise.UserService;
import com.srp.tools.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
public class UserController {
    @Autowired
    UserService userService;
    @GetMapping("/api/user/create")
    CreateOrLoginReturn createUser(String phone, String password){
        return userService.createUser(phone,password);
    }

    @GetMapping("/api/user/login")
   // CreateOrLoginReturn loginUser(String phone, String password){
    R loginUser(String phone, String password){
        CreateOrLoginReturn user =  userService.loginUser(phone,password);
        //登录成功,生成令牌,下发令牌
        if (user.getId() != null){
            Map<String, Object> claims = new HashMap<>();
            //此处要大写，在JwtUtils工具中会自动首字符大写
            claims.put("UserId", user.getId());

            String jwt = JwtUtils.generateJwt(claims); //jwt包含了当前登录的员工信息
            return R.success(jwt);
        }

        //登录失败, 返回错误信息
        return R.error("用户名或密码错误");
    }



    @PostMapping("/api/user/editInfo")
    EditUserInfoReturn editInformation(@RequestHeader("token")String token, MultipartFile avatar, String name) throws IOException {
        // 获取userId
        Claims claims = JwtUtils.parseJWT(token);
        String userId = claims.get("UserId",String.class);
        EditUserInfoReturn editInformation = userService.editInformation(userId,avatar,name);
        log.info("编辑用户信息"+userId+" "+avatar+" "+name+"完成");
        return editInformation;
    }

    @GetMapping("/api/user/info")
    GetUserInfoReturn getUserInfo(@RequestHeader("token")String token){
        Claims claims = JwtUtils.parseJWT(token);
        String userId = claims.get("UserId",String.class);
        return userService.getUserInfo(userId);
    }


}
